package item

import (
	"context"
	"fmt"
	"strings"
	"time"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	client "mall/service/recommended/common/gorseclient"
	"mall/service/recommended/rpc/internal/svc"
	"mall/service/recommended/rpc/types/recommended"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateItemLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateItemLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateItemLogic {
	return &CreateItemLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateItemLogic) CreateItem(in *recommended.ItemInfo) (*recommended.BaseRowAffectedResp, error) {
	if in.ItemId == nil || len(strings.TrimSpace(*in.ItemId)) == 0 {

	}
	logrus.Info(fmt.Sprintf("CreateItem ItemID: %+v", *in.ItemId))
	var item client.Item
	isHidden := false
	if in.IsHidden != nil && *in.IsHidden {
		isHidden = true
	}
	if len(in.Labels) > 0 {
		item.Labels = in.Labels
	}
	if len(in.Category) > 0 {
		item.Categories = in.Category
	}
	if in.Comment != nil && len(strings.TrimSpace(*in.Comment)) >= 0 {
		item.Comment = *in.Comment
	}
	item.ItemId = *in.ItemId
	item.IsHidden = isHidden
	now := modelx.FormatTime(time.Now(), "")
	item.Timestamp = now
	res, err := l.svcCtx.GorseClient.InsertItem(l.ctx, item)
	if err != nil {
		return nil, err
	}

	return &recommended.BaseRowAffectedResp{
		RowAffected: pointy.GetPointer(uint32(res.RowAffected)),
	}, nil
}
